/*
 * @Author: xiaosihan
 * @Date: 2025-08-24 10:00:00
 * @Last Modified by: xiaosihan
 * @Last Modified time: 2025-09-27 00:11:08
 */
import React from 'react';
import { makeAutoObservable } from 'mobx';
import dataApi from '@/api/dataApi';
import { message } from 'antd';
import { DesignData, OssFileData } from '@/types/type';

class DataViewerStore {
    constructor() {
        makeAutoObservable(this, {}, { deep: false });
    }

    // 状态管理
    designData: DesignData[] = [];
    ossFileData: OssFileData[] = [];
    designTotal = 0;
    ossFileTotal = 0;
    designLoading = false;
    ossFileLoading = false;
    designCurrentPage = 1;
    ossFileCurrentPage = 1;
    pageSize = 20; // 修改为每页20条数据
    addingData = false;
    sortingData: number | null = null;
    sortOrders: Record<number, number> = {};
    randomSettingData = false;
    resettingOssStatus = false;
    checkingOssUsageStatus = false;
    clearingDesignData = false;
    deletingAllDesignData = false;
    // OSS文件筛选条件
    ossFileFilter: { used?: string } = {};
    // 是否只显示非唯一的data值
    onlyDuplicateData = false;
    // 是否只显示data非空的值
    requireNonEmptyData = false;
    // 是否只显示非唯一的url值
    onlyDuplicateUrl = false;
    // 编辑状态
    editingId: number | null = null;
    editingData: string = '';
    editingOrder: number | null = null;
    updatingData = false;

    // 加载Design表数据
    loadDesignData = async (page: number, pageSize: number) => {
        this.designLoading = true;
        try {
            const response = await dataApi.get_design_data({ page, pageSize, onlyDuplicateData: this.onlyDuplicateData, requireNonEmptyData: this.requireNonEmptyData });
            if (response && response.status === 'success') {
                const data = response.data.data || [];
                this.designData = data;
                this.designTotal = response.data.total || 0;

                // 初始化排序值状态
                const orders: Record<number, number> = {};
                data.forEach((item: DesignData) => {
                    orders[item.id] = item.order || 0;
                });
                this.sortOrders = orders;
            }
        } catch (error) {
            console.error('加载Design数据失败:', error);
        } finally {
            this.designLoading = false;
        }
    }

    // 设置是否只显示非唯一的data值
    setOnlyDuplicateData = async (onlyDuplicateData: boolean) => {
        this.onlyDuplicateData = onlyDuplicateData;
        // 重置页码并重新加载数据
        this.designCurrentPage = 1;
        await this.loadDesignData(1, this.pageSize);
    };

    // 设置是否只显示data非空的值
    setRequireNonEmptyData = async (requireNonEmptyData: boolean) => {
        this.requireNonEmptyData = requireNonEmptyData;
        // 重置页码并重新加载数据
        this.designCurrentPage = 1;
        await this.loadDesignData(1, this.pageSize);
    };

    // 随机设置Design表数据
    handleRandomSetDesignData = async () => {
        this.randomSettingData = true;
        message.info('开始随机设置数据，请稍候...');
        try {
            // 由于randomSetDesignData函数不存在，使用addDesignData代替
            const response = await dataApi.design_random_set_data();
            if (response && response.status === 'success') {
                message.success(response.message || '数据设置成功！');
                // 重新加载数据，更新表格显示
                await this.loadDesignData(this.designCurrentPage, this.pageSize);
            } else {
                message.error('数据设置失败：' + (response?.message || '未知错误'));
            }
        } catch (error) {
            console.error('随机设置Design数据失败:', error);
            message.error('数据设置失败，请重试');
        } finally {
            this.randomSettingData = false;
        }
    }

    // 向Design表添加数据
    handleAddDesignData = async () => {
        this.addingData = true;
        message.info('开始添加数据，请稍候...');
        try {
            const response = await dataApi.design_add_data({});
            if (response && response.status === 'success') {
                message.success('数据添加成功！');
                // 重新加载数据，更新表格显示
                await this.loadDesignData(this.designCurrentPage, this.pageSize);
            } else {
                message.error('数据添加失败：' + (response?.message || '未知错误'));
            }
        } catch (error) {
            console.error('添加Design数据失败:', error);
            message.error('数据添加失败，请重试');
        } finally {
            this.addingData = false;
        }
    }

    // 处理排序值变化
    handleSortOrderChange = (id: number, value: number | null) => {
        if (value !== null) {
            this.sortOrders = {
                ...this.sortOrders,
                [id]: value
            };
        }
    }

    // 提交排序请求
    handleSortSubmit = async (id: number) => {
        const targetOrder = this.sortOrders[id];
        if (targetOrder === undefined) return;

        this.sortingData = id;
        message.info('正在移动数据，请稍候...');
        try {
            const response = await dataApi.design_reorder_data({ id, targetOrder });
            if (response && response.status === 'success') {
                message.success(response.message || '排序成功！');
                // 重新加载数据，更新表格显示
                await this.loadDesignData(this.designCurrentPage, this.pageSize);
            } else {
                message.error('排序失败：' + (response?.message || '未知错误'));
            }
        } catch (error) {
            console.error('排序失败:', error);
            message.error('排序失败，请重试');
        } finally {
            this.sortingData = null;
        }
    }

    // 设置OSS文件筛选条件
    setOssFileFilter = async (filter: { used?: string }) => {
        // 当选择"全部"时，不传递筛选条件
        this.ossFileFilter = filter.used === 'all' ? {} : filter;
        // 重置页码并重新加载数据
        this.ossFileCurrentPage = 1;
        await this.loadOssFileData(1, this.pageSize);
    };



    // 加载OSS文件数据
    loadOssFileData = async (page: number, pageSize: number) => {
        this.ossFileLoading = true;
        try {
            const response = await dataApi.oss_file_get_data({ page, pageSize, used: this.ossFileFilter.used, onlyDuplicateUrl: this.onlyDuplicateUrl });
            if (response && response.status === 'success') {
                this.ossFileData = response.data.data || [];
                this.ossFileTotal = response.data.total || 0;
            }
        } catch (error) {
            console.error('加载OSS文件数据失败:', error);
        } finally {
            this.ossFileLoading = false;
        }
    }

    // 设置是否只显示非唯一的url值
    setOnlyDuplicateUrl = async (onlyDuplicateUrl: boolean) => {
        this.onlyDuplicateUrl = onlyDuplicateUrl;
        // 重置页码并重新加载数据
        this.ossFileCurrentPage = 1;
        await this.loadOssFileData(1, this.pageSize);
    };

    // 重置OSS文件使用状态
    handleResetOssFileUsedStatus = async () => {
        this.resettingOssStatus = true;
        message.info('开始重置OSS文件使用状态，请稍候...');
        try {
            const response = await dataApi.oss_file_reset_used_status();
            if (response && response.status === 'success') {
                message.success(response.message || 'OSS文件使用状态重置成功！');
                // 重新加载数据，更新表格显示
                await this.loadOssFileData(this.ossFileCurrentPage, this.pageSize);
            } else {
                message.error('OSS文件使用状态重置失败：' + (response?.message || '未知错误'));
            }
        } catch (error) {
            console.error('重置OSS文件使用状态失败:', error);
            message.error('OSS文件使用状态重置失败，请重试');
        } finally {
            this.resettingOssStatus = false;
        }
    }

    // 检查OSS文件URL使用状态
    handleCheckOssFileUsageStatus = async () => {
        this.checkingOssUsageStatus = true;
        const startTime = Date.now(); // 记录开始时间
        message.info('开始检查OSS文件URL使用状态，请稍候...');
        try {
            const response = await dataApi.oss_file_check_usage_status();
            if (response && response.status === 'success') {
                message.success(response.message || 'OSS文件URL使用状态检查成功！');
                // 重新加载数据，更新表格显示
                await this.loadOssFileData(this.ossFileCurrentPage, this.pageSize);
            } else {
                message.error('OSS文件URL使用状态检查失败：' + (response?.message || '未知错误'));
            }
        } catch (error) {
            console.error('检查OSS文件URL使用状态失败:', error);
            message.error('OSS文件URL使用状态检查失败，请重试');
        } finally {
            this.checkingOssUsageStatus = false;
            const endTime = Date.now(); // 记录结束时间
            const elapsedTime = (endTime - startTime) / 1000; // 计算耗时（秒）
            message.info(`检查使用状态操作耗时: ${elapsedTime.toFixed(2)}秒`); // 显示耗时
        }
    };

    // 调用后端API查找匹配数据并更新（每次处理一对数据）
    handleMatchAndUpdateData = async () => {
        this.designLoading = true;
        this.ossFileLoading = true;
        message.info('开始查找匹配数据并更新，请稍候...');
        try {
            // 调用后端API进行匹配和更新
            const response = await dataApi.match_and_update_data();
            
            if (response && response.status === 'success') {
                if (response.data && response.data.matched) {
                    console.log(`成功匹配并更新数据: design.id=${response.data.designId}, oss_file.file_id=${response.data.ossFileId}`);
                    message.success('成功找到并处理了1条匹配的数据！');
                    // 重新加载数据，更新表格显示
                    await Promise.all([
                        this.loadDesignData(this.designCurrentPage, this.pageSize),
                        this.loadOssFileData(this.ossFileCurrentPage, this.pageSize)
                    ]);
                } else {
                    message.info(response.data ? response.data.message : '未找到匹配的数据');
                }
            } else {
                message.error(response ? response.message || '处理失败，请重试' : '处理失败，请重试');
            }
        } catch (error) {
            console.error('查找匹配数据失败:', error);
            message.error('查找匹配数据失败，请重试');
        } finally {
            this.designLoading = false;
            this.ossFileLoading = false;
        }
    };

    // 清空Design表data字段
    handleClearDesignData = async () => {
        this.clearingDesignData = true;
        message.info('开始清空Design表data字段，请稍候...');
        try {
            const response = await dataApi.design_clear_data();
            if (response && response.status === 'success') {
                message.success(response.message || 'Design表data字段清空成功！');
                // 重新加载数据，更新表格显示
                await this.loadDesignData(this.designCurrentPage, this.pageSize);
            } else {
                message.error('Design表data字段清空失败：' + (response?.message || '未知错误'));
            }
        } catch (error) {
            console.error('清空Design表data字段失败:', error);
            message.error('Design表data字段清空失败，请重试');
        } finally {
            this.clearingDesignData = false;
        }
    };

    // 删除Design表全部数据
    handleDeleteAllDesignData = async () => {
        // 确认对话框，防止误操作
        if (!window.confirm('确定要删除Design表中的全部数据吗？此操作不可恢复！')) {
            return;
        }

        this.deletingAllDesignData = true;
        message.info('开始删除Design表全部数据，请稍候...');
        try {
            const response = await dataApi.design_delete_all_data();
            if (response && response.status === 'success') {
                message.success(response.message || 'Design表全部数据删除成功！');
                // 重新加载数据，更新表格显示
                await this.loadDesignData(this.designCurrentPage, this.pageSize);
            } else {
                message.error('Design表全部数据删除失败：' + (response?.message || '未知错误'));
            }
        } catch (error) {
            console.error('删除Design表全部数据失败:', error);
            message.error('Design表全部数据删除失败，请重试');
        } finally {
            this.deletingAllDesignData = false;
        }
    };

    // 处理Design表分页变化
    handleDesignPageChange = async (page: number, pageSize: number) => {
        this.designCurrentPage = page;
        await this.loadDesignData(page, pageSize);
    }

    // 处理OSS文件表分页变化
    handleOssFilePageChange = async (page: number, pageSize: number) => {
        this.ossFileCurrentPage = page;
        await this.loadOssFileData(page, pageSize);
    }

    // 初始加载数据
    initializeData = async () => {
        await Promise.all([
            this.loadDesignData(1, this.pageSize),
            this.loadOssFileData(1, this.pageSize)
        ]);
    };

    // 开始编辑数据
    startEditing = (id: number, data: string, order: number | null) => {
        this.editingId = id;
        this.editingData = data || '';
        this.editingOrder = order;
    };

    // 处理数据字段变化
    handleEditDataChange = (e: React.ChangeEvent<HTMLTextAreaElement>) => {
        this.editingData = e.target.value;
    };

    // 处理排序字段变化
    handleEditOrderChange = (value: number | null) => {
        this.editingOrder = value;
    };

    // 提交编辑
    submitEdit = async () => {
        if (this.editingId === null) return;

        this.updatingData = true;
        message.info('正在更新数据，请稍候...');
        try {
            const response = await dataApi.design_update_data({ id: this.editingId, data: this.editingData, order: this.editingOrder });
            if (response && response.status === 'success') {
                message.success('数据更新成功！');
                // 重新加载数据，更新表格显示
                await this.loadDesignData(this.designCurrentPage, this.pageSize);
                this.cancelEdit();
            } else {
                message.error('数据更新失败：' + (response?.message || '未知错误'));
            }
        } catch (error) {
            console.error('更新数据失败:', error);
            message.error('数据更新失败，请重试');
        } finally {
            this.updatingData = false;
        }
    };

    // 取消编辑
    cancelEdit = () => {
        this.editingId = null;
        this.editingData = '';
        this.editingOrder = null;
    };
};

const dataViewerStore = new DataViewerStore();

export default dataViewerStore;